#include "FileManager.hpp"
#include <stdexcept>
#include <spdlog/spdlog.h>
#include <fmt/format.h>

FileManager::FileManager(std::filesystem::path path,std::vector<std::string> CameraIDList)
  : rootPath(path)
  , CameraID(CameraIDList)
{
  if(!std::filesystem::exists(path) || std::filesystem::status(path).type()!=std::filesystem::file_type::directory)
    throw std::runtime_error("The path is not exit or not directory");
}

FileManager::~FileManager()
{

}



std::list<long> FileManager::ScanRecordName()
{
  std::list<long> ret;
  for(auto const & dir_entry : std::filesystem::directory_iterator{rootPath})
  {
    long val;
    try
    {
      val=std::stoi(dir_entry.path().filename());
    }
    catch(const std::invalid_argument & e)
    {
      spdlog::warn("Unknow directory name : {}",dir_entry.path().string());
    }
    ret.push_back(val);
  }
  return ret;
}


bool FileManager::CreateRecord(long id)
{
  return std::filesystem::create_directory(rootPath/(std::stringstream()<<id).str());
}

bool FileManager::DeleteRecord(long id)
{
  return std::filesystem::remove_all((std::stringstream()<<id).str());
}


bool FileManager::CheckRecordExists(long id)
{
  std::filesystem::path RecordPath=rootPath/(std::stringstream()<<id).str();
  return std::filesystem::exists(RecordPath);
}

bool FileManager::CheckRecordFinish(long id)
{
  std::filesystem::path RecordPath=rootPath/std::to_string(id);
  for(const auto & i : CameraID)
  {
    if(!std::filesystem::exists(RecordPath/fmt::format("{}.mkv",i)) 
    || !std::filesystem::exists(RecordPath/fmt::format("{}.frame",i))
    )
      return false;
  }
  return true;
}

std::string FileManager::GetRecordPath(long id)
{
  return rootPath/std::to_string(id);
}

bool FileManager::CheckRecordHandle(long id)
{
  std::filesystem::path RecordPath=rootPath/(std::stringstream()<<id).str();
    if(!std::filesystem::exists(RecordPath/"Pose3D.txt") 
    || !std::filesystem::exists(RecordPath/"smpl.mp4")
    )
    return false;
  return true;
}

